package data;

import java.lang.reflect.Field;
import java.util.Date;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class DataPlayer {
	public static DBCollection players;
	
	public static boolean isDBValueType(Field f) {
		return f.getClass().isPrimitive();
//		Class<?> cla = f.getClass();
//		if (cla.equals(int.class)) return true;
//		if (cla.equals(Date.class)) return true;
//		if (cla.equals(String.class)) return true;
//		if (cla.equals(float.class)) return true;
//		if (cla.equals(long.class)) return true;
//		if (cla.equals(Double.class)) return true;
//		cla.isp
//		return false;
	}
	
	public static void initDB(DB db) {
		players = db.getCollection("DataPlayer");
		players.ensureIndex("name");
	}
	
	public BasicDBObject doc;

	public String uuid;
	public String name;
	public String level;
	public Date registerTime;
	public DataMap map;
	public DataPet pets[];
	
	public void load() {
		
	}

	public void saveAll() throws IllegalArgumentException, IllegalAccessException {
		if (doc == null) {
			Field fields[] = DataPlayer.class.getFields();
			doc = new BasicDBObject();
			Object value;
			for (Field f: fields) {
				value = f.get(this);				
				if (value instanceof IMongoObject) {					
					((IMongoObject) value).save();
					doc.put(f.getName(), ((IMongoObject)value).getDoc());
					continue;
				}
				if (isDBValueType(f)) {
					doc.put(f.getName(), value);
					continue;
				}
			}
			BasicDBList list = new BasicDBList();
			for (DataPet pet: pets) {
				pet.save();
				list.add(pet.getDoc());
			}
			doc.put("pets", list);
		}
		players.save(doc);
	}
	
	
}
